{% extends "base.html" %}

{% block title %}{{ page_title }} - 乒乓球培训管理系统{% endblock %}

{% block extra_css %}
<style>
    .statistics-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
        text-align: center;
    }

    .period-selector {
        background: rgba(255,255,255,0.1);
        border-radius: 10px;
        padding: 1rem;
        margin-top: 1.5rem;
    }

    .period-btn {
        background: rgba(255,255,255,0.2);
        border: 1px solid rgba(255,255,255,0.3);
        color: white;
        border-radius: 20px;
        padding: 0.5rem 1rem;
        margin: 0.25rem;
        transition: all 0.3s ease;
    }

    .period-btn:hover,
    .period-btn.active {
        background: rgba(255,255,255,0.3);
        color: white;
        border-color: rgba(255,255,255,0.5);
    }

    .stats-overview {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .stat-card {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        text-align: center;
        transition: transform 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, #28a745, #20c997);
    }

    .stat-card.income::before {
        background: linear-gradient(90deg, #28a745, #20c997);
    }

    .stat-card.expense::before {
        background: linear-gradient(90deg, #dc3545, #e83e8c);
    }

    .stat-card.profit::before {
        background: linear-gradient(90deg, #007bff, #6610f2);
    }

    .stat-card.transactions::before {
        background: linear-gradient(90deg, #ffc107, #fd7e14);
    }

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
    }

    .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 1rem;
        font-size: 1.5rem;
        color: white;
    }

    .stat-icon.income {
        background: linear-gradient(135deg, #28a745, #20c997);
    }

    .stat-icon.expense {
        background: linear-gradient(135deg, #dc3545, #e83e8c);
    }

    .stat-icon.profit {
        background: linear-gradient(135deg, #007bff, #6610f2);
    }

    .stat-icon.transactions {
        background: linear-gradient(135deg, #ffc107, #fd7e14);
    }

    .stat-value {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 0.5rem;
        color: #495057;
    }

    .stat-label {
        color: #6c757d;
        font-size: 0.9rem;
        margin-bottom: 0.5rem;
    }

    .stat-change {
        font-size: 0.8rem;
        font-weight: 500;
    }

    .stat-change.positive {
        color: #28a745;
    }

    .stat-change.negative {
        color: #dc3545;
    }

    .chart-container {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
    }

    .chart-title {
        font-size: 1.2rem;
        font-weight: 600;
        color: #495057;
        margin-bottom: 1.5rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .chart-wrapper {
        position: relative;
        height: 400px;
    }

    .payment-methods-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-top: 1rem;
    }

    .payment-method-card {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 1.5rem;
        text-align: center;
        border: 2px solid transparent;
        transition: all 0.3s ease;
    }

    .payment-method-card:hover {
        border-color: #007bff;
        transform: translateY(-3px);
    }

    .payment-method-icon {
        font-size: 2rem;
        margin-bottom: 1rem;
    }

    .payment-method-icon.alipay {
        color: #1677ff;
    }

    .payment-method-icon.wechat {
        color: #07c160;
    }

    .payment-method-icon.unionpay {
        color: #e21f2f;
    }

    .payment-method-icon.cash {
        color: #28a745;
    }

    .payment-method-icon.bank {
        color: #007bff;
    }

    .payment-method-icon.pos {
        color: #fd7e14;
    }

    .campus-stats-table {
        background: white;
        border-radius: 15px;
        overflow: hidden;
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
    }

    .table thead th {
        background: #f8f9fa;
        border-bottom: 2px solid #dee2e6;
        font-weight: 600;
        color: #495057;
    }

    .user-distribution {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
    }

    .distribution-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1rem;
        margin-bottom: 0.5rem;
        background: #f8f9fa;
        border-radius: 8px;
        transition: all 0.3s ease;
    }

    .distribution-item:hover {
        background: #e9ecef;
        transform: translateX(5px);
    }

    .distribution-label {
        font-weight: 500;
        color: #495057;
    }

    .distribution-value {
        font-weight: bold;
        color: #007bff;
    }

    .distribution-bar {
        width: 100%;
        height: 8px;
        background: #e9ecef;
        border-radius: 4px;
        margin-top: 0.5rem;
        overflow: hidden;
    }

    .distribution-fill {
        height: 100%;
        background: linear-gradient(90deg, #007bff, #6610f2);
        border-radius: 4px;
        transition: width 0.8s ease;
    }

    .export-section {
        background: white;
        border-radius: 15px;
        padding: 2rem;
        margin-bottom: 2rem;
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        text-align: center;
    }

    .export-btn {
        background: linear-gradient(45deg, #28a745, #20c997);
        border: none;
        border-radius: 25px;
        padding: 0.75rem 2rem;
        color: white;
        font-weight: 500;
        margin: 0.5rem;
        transition: all 0.3s ease;
    }

    .export-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(40,167,69,0.3);
        color: white;
    }

    .date-range-form {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 1.5rem;
        margin-bottom: 2rem;
    }

    .no-data-message {
        text-align: center;
        padding: 3rem 2rem;
        color: #6c757d;
    }

    .no-data-message i {
        font-size: 4rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }

    @media (max-width: 768px) {
        .stats-overview {
            grid-template-columns: 1fr;
        }

        .payment-methods-grid {
            grid-template-columns: repeat(2, 1fr);
        }

        .stat-value {
            font-size: 1.5rem;
        }

        .chart-wrapper {
            height: 300px;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="statistics-header">
        <h2 class="mb-3">
            <i class="fas fa-chart-bar me-2"></i>财务统计报表
        </h2>
        <p class="mb-0 opacity-75">系统财务数据分析与报表</p>

        <!-- 时间周期选择 -->
        <div class="period-selector">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="btn-group flex-wrap" role="group">
                        <button type="button" class="btn period-btn {{ 'active' if period == 'today' }}"
                                onclick="changePeriod('today')">今日</button>
                        <button type="button" class="btn period-btn {{ 'active' if period == 'week' }}"
                                onclick="changePeriod('week')">本周</button>
                        <button type="button" class="btn period-btn {{ 'active' if period == 'month' }}"
                                onclick="changePeriod('month')">本月</button>
                        <button type="button" class="btn period-btn {{ 'active' if period == 'quarter' }}"
                                onclick="changePeriod('quarter')">本季度</button>
                        <button type="button" class="btn period-btn {{ 'active' if period == 'year' }}"
                                onclick="changePeriod('year')">本年度</button>
                        <button type="button" class="btn period-btn {{ 'active' if period == 'custom' }}"
                                onclick="showCustomDateRange()">自定义</button>
                    </div>
                </div>
                <div class="col-md-4 text-md-end mt-3 mt-md-0">
                    <small class="opacity-75">
                        统计时间：{{ start_time.strftime('%Y-%m-%d') }} 至 {{ end_time.strftime('%Y-%m-%d') }}
                    </small>
                </div>
            </div>
        </div>
    </div>

    <!-- 自定义日期范围 -->
    <div class="date-range-form" id="customDateForm" style="display: {{ 'block' if period == 'custom' else 'none' }}">
        <form method="GET" class="row g-3 align-items-end">
            <input type="hidden" name="period" value="custom">
            <div class="col-md-4">
                <label class="form-label">开始日期</label>
                <input type="date" class="form-control" name="start_date"
                       value="{{ start_date if start_date }}" required>
            </div>
            <div class="col-md-4">
                <label class="form-label">结束日期</label>
                <input type="date" class="form-control" name="end_date"
                       value="{{ end_date if end_date }}" required>
            </div>
            <div class="col-md-4">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-search me-2"></i>查询
                </button>
                <button type="button" class="btn btn-outline-secondary ms-2" onclick="hideDateRange()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </form>
    </div>

    <!-- 统计概览 -->
    {% if financial_data %}
    <div class="stats-overview">
        <div class="stat-card income">
            <div class="stat-icon income">
                <i class="fas fa-arrow-up"></i>
            </div>
            <div class="stat-value">¥{{ "%.2f"|format(financial_data.total_income) }}</div>
            <div class="stat-label">总收入</div>
            <div class="stat-change positive">
                <i class="fas fa-arrow-up me-1"></i>充值收入
            </div>
        </div>

        <div class="stat-card expense">
            <div class="stat-icon expense">
                <i class="fas fa-arrow-down"></i>
            </div>
            <div class="stat-value">¥{{ "%.2f"|format(financial_data.total_expense) }}</div>
            <div class="stat-label">总支出</div>
            <div class="stat-change negative">
                <i class="fas fa-arrow-down me-1"></i>预约消费
            </div>
        </div>

        <div class="stat-card profit">
            <div class="stat-icon profit">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="stat-value">¥{{ "%.2f"|format(financial_data.total_income - financial_data.total_expense) }}</div>
            <div class="stat-label">净流入</div>
            <div class="stat-change {{ 'positive' if (financial_data.total_income - financial_data.total_expense) >= 0 else 'negative' }}">
                <i class="fas fa-{{ 'plus' if (financial_data.total_income - financial_data.total_expense) >= 0 else 'minus' }} me-1"></i>
                收支差额
            </div>
        </div>

        <div class="stat-card transactions">
            <div class="stat-icon transactions">
                <i class="fas fa-exchange-alt"></i>
            </div>
            <div class="stat-value">{{ financial_data.transaction_count }}</div>
            <div class="stat-label">交易笔数</div>
            <div class="stat-change positive">
                <i class="fas fa-list me-1"></i>总交易数
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 收入趋势图表 -->
        <div class="col-lg-8">
            <div class="chart-container">
                <div class="chart-title">
                    <i class="fas fa-chart-line"></i>收入趋势分析
                </div>
                {% if financial_data.daily_data %}
                <div class="chart-wrapper">
                    <canvas id="incomeChart"></canvas>
                </div>
                {% else %}
                <div class="no-data-message">
                    <i class="fas fa-chart-line"></i>
                    <h5>暂无数据</h5>
                    <p>所选时间段内没有收入记录</p>
                </div>
                {% endif %}
            </div>
        </div>

        <!-- 支付方式分布 -->
        <div class="col-lg-4">
            <div class="chart-container">
                <div class="chart-title">
                    <i class="fas fa-credit-card"></i>支付方式分布
                </div>
                {% if financial_data.payment_methods %}
                <div class="payment-methods-grid">
                    {% for method, data in financial_data.payment_methods.items() %}
                    <div class="payment-method-card">
                        <div class="payment-method-icon {{ method }}">
                            {% if method == 'alipay' %}
                                <i class="fab fa-alipay"></i>
                            {% elif method == 'wechat' %}
                                <i class="fab fa-weixin"></i>
                            {% elif method == 'unionpay' %}
                                <i class="fas fa-credit-card"></i>
                            {% elif method == 'cash' %}
                                <i class="fas fa-money-bill-wave"></i>
                            {% elif method == 'bank_transfer' %}
                                <i class="fas fa-university"></i>
                            {% elif method == 'pos' %}
                                <i class="fas fa-credit-card"></i>
                            {% else %}
                                <i class="fas fa-question-circle"></i>
                            {% endif %}
                        </div>
                        <div class="fw-bold">¥{{ "%.2f"|format(data.amount) }}</div>
                        <small class="text-muted">{{ data.count }}笔</small>
                        <div>
                            <small>
                                {% if method == 'alipay' %}支付宝
                                {% elif method == 'wechat' %}微信支付
                                {% elif method == 'unionpay' %}银联支付
                                {% elif method == 'cash' %}现金
                                {% elif method == 'bank_transfer' %}银行转账
                                {% elif method == 'pos' %}POS机
                                {% else %}{{ method }}
                                {% endif %}
                            </small>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="no-data-message">
                    <i class="fas fa-credit-card"></i>
                    <h6>暂无支付数据</h6>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- 校区财务统计 -->
    {% if campus_stats %}
    <div class="campus-stats-table">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th colspan="4" class="text-center bg-primary text-white">
                            <i class="fas fa-building me-2"></i>校区财务统计
                        </th>
                    </tr>
                    <tr>
                        <th>校区名称</th>
                        <th>充值金额</th>
                        <th>交易笔数</th>
                        <th>平均单笔</th>
                    </tr>
                </thead>
                <tbody>
                    {% for campus in campus_stats %}
                    <tr>
                        <td>
                            <i class="fas fa-map-marker-alt me-2 text-primary"></i>
                            {{ campus.campus_name }}
                        </td>
                        <td class="fw-bold text-success">
                            ¥{{ "%.2f"|format(campus.total_amount) }}
                        </td>
                        <td>
                            <span class="badge bg-info">{{ campus.transaction_count }}</span>
                        </td>
                        <td>
                            ¥{{ "%.2f"|format(campus.total_amount / campus.transaction_count if campus.transaction_count > 0 else 0) }}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
    {% endif %}

    <!-- 用户余额分布 -->
    {% if user_stats %}
    <div class="row mt-4">
        <div class="col-12">
            <div class="user-distribution">
                <div class="chart-title">
                    <i class="fas fa-users"></i>用户余额分布
                </div>

                {% for stat in user_stats %}
                <div class="distribution-item">
                    <div class="distribution-label">{{ stat.range }}</div>
                    <div class="distribution-value">{{ stat.count }} 人</div>
                </div>
                <div class="distribution-bar">
                    <div class="distribution-fill" style="width: {{ (stat.count / user_stats|map(attribute='count')|sum * 100) if user_stats|map(attribute='count')|sum > 0 else 0 }}%"></div>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
    {% endif %}

    <!-- 导出功能 -->
    <div class="export-section">
        <h5 class="mb-3">
            <i class="fas fa-download me-2"></i>数据导出
        </h5>
        <p class="text-muted mb-4">导出当前时间段的财务数据</p>

        <div class="d-flex justify-content-center flex-wrap">
            <button type="button" class="btn export-btn" onclick="exportFinancialData('excel')">
                <i class="fas fa-file-excel me-2"></i>导出Excel
            </button>
            <button type="button" class="btn export-btn" onclick="exportFinancialData('csv')">
                <i class="fas fa-file-csv me-2"></i>导出CSV
            </button>
            <button type="button" class="btn export-btn" onclick="exportFinancialData('pdf')">
                <i class="fas fa-file-pdf me-2"></i>导出PDF报表
            </button>
            <button type="button" class="btn export-btn" onclick="printReport()">
                <i class="fas fa-print me-2"></i>打印报表
            </button>
        </div>
    </div>

    {% else %}
    <!-- 无数据提示 -->
    <div class="no-data-message">
        <i class="fas fa-chart-bar"></i>
        <h4>暂无财务数据</h4>
        <p class="text-muted">所选时间段内没有找到财务数据</p>
        <button type="button" class="btn btn-primary" onclick="changePeriod('month')">
            <i class="fas fa-calendar me-2"></i>查看本月数据
        </button>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function() {
    // 初始化图表
    {% if financial_data and financial_data.daily_data %}
    initIncomeChart();
    {% endif %}

    // 页面加载动画
    $('.stat-card').each(function(index) {
        $(this).delay(index * 100).fadeIn(600);
    });

    $('.chart-container').each(function(index) {
        $(this).delay(index * 200 + 400).fadeIn(600);
    });
});

// 收入趋势图表
function initIncomeChart() {
    const ctx = document.getElementById('incomeChart');
    if (!ctx) return;

    const dailyData = {{ financial_data.daily_data | tojson }};
    const dates = Object.keys(dailyData).sort();
    const amounts = dates.map(date => parseFloat(dailyData[date]));

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: dates.map(date => {
                const d = new Date(date);
                return (d.getMonth() + 1) + '/' + d.getDate();
            }),
            datasets: [{
                label: '日收入金额',
                data: amounts,
                borderColor: '#28a745',
                backgroundColor: 'rgba(40, 167, 69, 0.1)',
                borderWidth: 3,
                fill: true,
                tension: 0.4,
                pointBackgroundColor: '#28a745',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 5
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: '每日收入趋势'
                },
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '¥' + value.toFixed(2);
                        }
                    },
                    grid: {
                        color: 'rgba(0,0,0,0.1)'
                    }
                },
                x: {
                    grid: {
                        color: 'rgba(0,0,0,0.1)'
                    }
                }
            },
            elements: {
                point: {
                    hoverRadius: 8
                }
            }
        }
    });
}

// 改变时间周期
function changePeriod(period) {
    window.location.href = '{{ url_for("admin_accounts.financial_statistics") }}?period=' + period;
}

// 显示自定义日期范围
function showCustomDateRange() {
    $('#customDateForm').slideDown();
}

// 隐藏日期范围选择
function hideDateRange() {
    $('#customDateForm').slideUp();
    window.location.href = '{{ url_for("admin_accounts.financial_statistics") }}?period=month';
}

// 导出财务数据
function exportFinancialData(format) {
    const params = new URLSearchParams({
        period: '{{ period }}',
        {% if start_date %}start_date: '{{ start_date }}',{% endif %}
        {% if end_date %}end_date: '{{ end_date }}',{% endif %}
        format: format
    });

    const exportUrl = '{{ url_for("admin_accounts.api_export_financial_data") }}?' + params.toString();

    // 创建下载链接
    const link = document.createElement('a');
    link.href = exportUrl;
    link.download = '';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    showAlert(`财务数据(${format.toUpperCase()})导出中，请稍候...`, 'info');
}

// 打印报表
function printReport() {
    // 隐藏不需要打印的元素
    const noPrintElements = document.querySelectorAll('.btn, .export-section, nav, .breadcrumb');
    noPrintElements.forEach(el => el.style.display = 'none');

    // 执行打印
    window.print();

    // 恢复隐藏的元素
    noPrintElements.forEach(el => el.style.display = '');
}

// 显示提示信息
function showAlert(message, type = 'info') {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;

    $('body').append(alertHtml);

    // 3秒后自动隐藏
    setTimeout(() => {
        $('.alert').fadeOut();
    }, 3000);
}

// 实时更新数据（可选）
function updateStatistics() {
    // 可以实现定时刷新统计数据
    console.log('更新统计数据...');
}

// 每5分钟更新一次数据
// setInterval(updateStatistics, 5 * 60 * 1000);

// 键盘快捷键
$(document).keydown(function(e) {
    // Ctrl + P 打印
    if (e.ctrlKey && e.key === 'p') {
        e.preventDefault();
        printReport();
    }

    // Ctrl + E 导出Excel
    if (e.ctrlKey && e.key === 'e') {
        e.preventDefault();
        exportFinancialData('excel');
    }

    // 数字键快速切换周期
    if (e.key >= '1' && e.key <= '5') {
        const periods = ['today', 'week', 'month', 'quarter', 'year'];
        const period = periods[parseInt(e.key) - 1];
        if (period) {
            changePeriod(period);
        }
    }
});

// 动画效果
window.addEventListener('load', function() {
    // 数字动画
    $('.stat-value').each(function() {
        const $this = $(this);
        const finalValue = $this.text();

        // 提取数字部分
        const match = finalValue.match(/[\d,.]+/);
        if (match) {
            const numValue = parseFloat(match[0].replace(/,/g, ''));
            const prefix = finalValue.substring(0, match.index);
            const suffix = finalValue.substring(match.index + match[0].length);

            $({ value: 0 }).animate({ value: numValue }, {
                duration: 1000,
                easing: 'swing',
                step: function() {
                    $this.text(prefix + Math.ceil(this.value).toLocaleString() + suffix);
                },
                complete: function() {
                    $this.text(finalValue);
                }
            });
        }
    });

    // 进度条动画
    $('.distribution-fill').each(function() {
        const width = $(this).css('width');
        $(this).css('width', '0').animate({ width: width }, 1000);
    });
});
</script>
{% endblock %}